package com.zx.idc.backend.gui.api.management.basicdata.query.impl;

import com.alibaba.fastjson.JSON;
import com.zx.idc.backend.gui.api.commom.entity.CommandModel;
import com.zx.idc.backend.gui.api.management.basicdata.query.IdcBasicDataManagementService;
import com.zx.idc.backend.gui.sys.login.MailClient;
import com.zx.idc.common.attributes.SystemAttributes;
import com.zx.idc.ds.common.constant.ReportStatusConstant;
import com.zx.idc.ds.ins.entity.InsAdminControl;
import com.zx.idc.ds.ins.service.IInsAdminControlService;
import com.zx.idc.ds.tlog.entity.TLogAlarm;
import com.zx.idc.ds.tlog.factory.TLogAlarmFactory;
import com.zx.idc.ds.tlog.service.ITLogAlarmService;
import com.zx.idc.xml.entity.returninfo.ReturnInfo;
import com.zx.idc.xml.entity.returninfo.returndata.ReturnData;
import com.zx.idc.xml.entity.returninfo.returndata.house.House;
import com.zx.idc.xml.entity.returninfo.returndata.user.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 基础数据核验处理服务实现
 *
 * @author rxliuli
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class IdcBasicDataManagementServiceImpl implements IdcBasicDataManagementService {

    private static final Logger LOG = LoggerFactory.getLogger(IdcBasicDataManagementServiceImpl.class);

    @Autowired
    private IInsAdminControlService iInsAdminControlService;

    @Autowired
    private ITLogAlarmService itLogAlarmService;

    @Autowired
    private MailClient mailClient;

    @Override
    public void verifyHandler(ReturnInfo returnInfo, CommandModel commandModel) {
        LOG.info("基础数据核验处理指令执行开始,指令ID为：{}", commandModel.getCommand());
        try {
            //记录管控指令
            InsAdminControl insAdminControl = new InsAdminControl()
                .setInsType(SystemAttributes.INS_TYPE_DATABASE_CHECK)
                .setIdcId(returnInfo.getIdcId())
                .setCreateTime(returnInfo.getTimeStamp())
                .setCommandId(" ")
                .setReportStatus(ReportStatusConstant.NOT_REPORTED)
                .setInsContents(JSON.toJSONString(returnInfo));
            iInsAdminControlService.insert(insAdminControl);
            StringBuilder alarmId = new StringBuilder();
            ReturnData returnData = returnInfo.getReturnData();
            if (returnData == null) {
                alarmId.append(insertTlogAlarm(TLogAlarm.VERIFY_TYPE_OPER_COMPANY, returnInfo.getIdcId(), returnInfo.getReturnMsg()));
            } else {
                List<House> house = returnData.getHouse();
                if (house.size() > 0) {
                    house.forEach(vo -> {
                        boolean onlyHouseId = true;
                        if (vo.getIpSegId() > 0) {
                            alarmId.append(insertTlogAlarm(TLogAlarm.VERIFY_TYPE_IP_ADDRESS, String.valueOf(vo.getIpSegId()),
                                "ID为 " + vo.getIpSegId() + " 的IP地址数据存在问题")).append("，");
                            onlyHouseId = false;
                        }
                        if (vo.getFrameInfoId() > 0) {
                            alarmId.append(insertTlogAlarm(TLogAlarm.VERIFY_TYPE_FRAME_INFO, String.valueOf(vo.getFrameInfoId()),
                                "ID为 " + vo.getFrameInfoId() + " 的机架信息数据存在问题")).append("，");
                            onlyHouseId = false;
                        }
                        if (vo.getGatewayId() > 0) {
                            alarmId.append(insertTlogAlarm(TLogAlarm.VERIFY_TYPE_HOUSE_LINK_INFO, String.valueOf(vo.getHouseId()),
                                "ID为 " + vo.getGatewayId() + " 的出入口信息数据存在问题")).append("，");
                            onlyHouseId = false;
                        }
                        if (onlyHouseId) {
                            alarmId.append(insertTlogAlarm(TLogAlarm.VERIFY_TYPE_HOUSE_INFO, String.valueOf(vo.getHouseId()),
                                "ID为 " + vo.getHouseId() + " 的机房信息数据存在问题")).append("，");
                        }
                    });
                }
                List<User> user = returnData.getUser();
                if (user.size() > 0) {
                    user.forEach(vo -> {
                        boolean onlyUserId = true;
                        if (vo.getService().size() > 0) {
                            vo.getService().forEach(service -> {
                                StringBuilder comments = new StringBuilder();
                                StringBuilder dealId = new StringBuilder();
                                dealId.append(vo.getUserId()).append("，").append(service.getServiceId());
                                if (service.getDomainId() > 0) {
                                    comments.append(" 域名信息 ");
                                    dealId.append("，").append(service.getDomainId());
                                }
                                if (service.getHhId() > 0) {
                                    comments.append(" 占用机房信息 ");
                                    dealId.append("，").append(service.getDomainId());
                                }
                                alarmId.append(insertTlogAlarm(TLogAlarm.VERIFY_TYPE_SERVICE_INFO, dealId.toString(),
                                    "ID为 " + service.getServiceId() + " 的应用服务信息的" + comments.toString() + "数据存在问题")).append("，");
                            });
                            onlyUserId = false;
                        }
                        if (vo.getHhId() > 0) {
                            alarmId.append(insertTlogAlarm(TLogAlarm.VERIFY_TYPE_HOUSE_HOLD_INFO, String.valueOf(vo.getUserId()) + "，" + String.valueOf(vo.getHhId()),
                                "ID为 " + vo.getHhId() + " 的占用机房信息数据存在问题")).append("，");
                            onlyUserId = false;
                        }
                        if (onlyUserId) {
                            alarmId.append(insertTlogAlarm(TLogAlarm.VERIFY_TYPE_CUSTOMER, String.valueOf(vo.getUserId()),
                                "ID为 " + vo.getUserId() + " 的客户信息数据存在问题")).append("，");
                        }
                    });
                }
            }
            mailClient.sendAlarmEmail("有新的告警日志生成，来自基础数据核验处理", "请及时查看ID为" + alarmId.substring(0, alarmId.length() - 1) + "的告警日志，并进行相应处理，处理完成后请及时将处理后的基础数据进行重新上报!");
            LOG.info("基础数据核验处理指令执行成功");
        } catch (Exception e) {
            LOG.error("基础数据核验处理指令执行失败", e);
            throw new RuntimeException(e);
        }
    }

    private Integer insertTlogAlarm(Integer verifyType, String dealId, String comments) {
        TLogAlarm basicVerifyHandlerTLogAlarm = TLogAlarmFactory.getBasicVerifyHandlerTLogAlarm(verifyType, dealId, comments);
        itLogAlarmService.insert(basicVerifyHandlerTLogAlarm);
        return basicVerifyHandlerTLogAlarm.getId();
    }

}
